import { Anthropic, IModelAdapter } from "./IModelAdapter";

/**
 * 抽象适配器基类
 * 提供通用的功能和默认实现
 */
abstract class BaseModelAdapter implements IModelAdapter {
    protected apiKey: string;
    protected baseURL: string;
    protected adapterName: string;

    constructor(apiKey: string, baseURL: string, adapterName: string) {
        this.apiKey = apiKey;
        this.baseURL = baseURL;
        this.adapterName = adapterName;
    }

    abstract create(): Anthropic;
    abstract getSupportedModels(): string[];

    getName(): string {
        return this.adapterName;
    }

    /**
     * 通用的消息转换方法
     * 子类可以重写此方法来实现特定的转换逻辑
     */
    protected transformMessages(messages: any[]): any[] {
        return messages.map(msg => {
            if (typeof msg.content === 'string') {
                return {
                    role: msg.role,
                    content: msg.content
                };
            }
            // 处理复杂内容格式（如包含图片等）
            if (Array.isArray(msg.content)) {
                const textContent = msg.content
                    .filter((item: any) => item.type === 'text')
                    .map((item: any) => item.text)
                    .join('\n');
                return {
                    role: msg.role,
                    content: textContent
                };
            }
            return msg;
        });
    }

    /**
     * 转换 Anthropic tools 格式到 OpenAI tools 格式
     */
    protected transformTools(anthropicTools: any[]): any[] {
        if (!anthropicTools || !Array.isArray(anthropicTools)) {
            return [];
        }

        return anthropicTools.map(tool => ({
            type: 'function',
            function: {
                name: tool.name,
                description: tool.description,
                parameters: tool.input_schema || {}
            }
        }));
    }

    /**
     * 转换 Anthropic tool_choice 格式到 OpenAI tool_choice 格式
     */
    protected transformToolChoice(anthropicToolChoice: any): any {
        if (!anthropicToolChoice) {
            return undefined;
        }

        // Anthropic 格式: "auto" | "any" | {"type": "tool", "name": "tool_name"}
        // OpenAI 格式: "none" | "auto" | {"type": "function", "function": {"name": "function_name"}}

        if (typeof anthropicToolChoice === 'string') {
            switch (anthropicToolChoice) {
                case 'auto':
                    return 'auto';
                case 'any':
                    return 'auto'; // OpenAI 没有 'any'，映射到 'auto'
                default:
                    return 'auto';
            }
        }

        if (typeof anthropicToolChoice === 'object' && anthropicToolChoice.type === 'tool') {
            return {
                type: 'function',
                function: {
                    name: anthropicToolChoice.name
                }
            };
        }

        return 'auto'; // 默认值
    }

    /**
     * 通用的结束原因映射
     * 子类可以重写此方法来实现特定的映射逻辑
     */
    protected mapFinishReason(finishReason: string): string {
        const reasonMap: { [key: string]: string } = {
            'stop': 'end_turn',
            'length': 'max_tokens',
            'content_filter': 'stop_sequence',
            'function_call': 'tool_use',
            'tool_calls': 'tool_use'  // OpenAI 使用 'tool_calls' 作为工具调用的结束原因
        };
        return reasonMap[finishReason] || 'end_turn';
    }
}

/**
 * Qwen-plus兼容适配器
 * 将Anthropic SDK的调用转换为Qwen-plus兼容的OpenAPI格式
 */
export class QwenAnthropicAdapter extends BaseModelAdapter {
    constructor(apiKey: string, baseURL: string = 'https://dashscope.aliyuncs.com/compatible-mode') {
        super(apiKey, baseURL, 'QwenAnthropicAdapter');
    }

    getSupportedModels(): string[] {
        return ['qwen3-coder-plus'];
    }

    /**
     * 转换OpenAI响应格式到Anthropic格式
     */
    private transformResponse(openaiResponse: any): any {
        const choice = openaiResponse.choices?.[0];
        if (!choice) {
            throw new Error('Invalid response format from Qwen API');
        }

        const content: any[] = [];

        // 添加文本内容（如果存在）
        if (choice.message?.content) {
            content.push({
                type: 'text',
                text: choice.message.content
            });
        }

        // 处理工具调用（如果存在）
        if (choice.message?.tool_calls && Array.isArray(choice.message.tool_calls)) {
            choice.message.tool_calls.forEach((toolCall: any) => {
                if (toolCall.type === 'function') {
                    content.push({
                        type: 'tool_use',
                        id: toolCall.id || `call_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`,
                        name: toolCall.function.name,
                        input: this.parseToolInput(toolCall.function.arguments)
                    });
                }
            });
        }

        // 如果没有内容，添加空文本
        if (content.length === 0) {
            content.push({
                type: 'text',
                text: ''
            });
        }

        return {
            id: openaiResponse.id || `msg_${Date.now()}`,
            type: 'message',
            role: 'assistant',
            content: content,
            model: openaiResponse.model || 'qwen-plus',
            stop_reason: this.mapFinishReason(choice.finish_reason),
            stop_sequence: null,
            usage: {
                input_tokens: openaiResponse.usage?.prompt_tokens || 0,
                output_tokens: openaiResponse.usage?.completion_tokens || 0
            }
        };
    }

    /**
     * 解析工具调用参数
     */
    private parseToolInput(argumentsStr: string): any {
        try {
            return JSON.parse(argumentsStr || '{}');
        } catch (error) {
            console.warn('Failed to parse tool arguments:', argumentsStr, error);
            return {};
        }
    }

    /**
     * 自定义fetch函数，处理API调用转换
     */
    private createCustomFetch() {
        return async (url: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
            const urlString = url.toString();

            // 拦截Anthropic的messages端点
            if (urlString.endsWith('/v1/messages')) {
                const qwenUrl = urlString.replace('/v1/messages', '/v1/chat/completions');

                // 解析原始请求体
                const originalBody = init?.body ? JSON.parse(init.body as string) : {};

                // 转换为OpenAI格式的请求体
                const qwenBody: any = {
                    model: originalBody.model || 'qwen-plus',
                    messages: this.transformMessages(originalBody.messages || []),
                    max_tokens: originalBody.max_tokens,
                    temperature: originalBody.temperature,
                    top_p: originalBody.top_p,
                    stream: originalBody.stream || false,
                    stop: originalBody.stop_sequences
                };

                // 添加 tools 转换
                if (originalBody.tools && Array.isArray(originalBody.tools)) {
                    qwenBody.tools = this.transformTools(originalBody.tools);

                    // 如果有 tool_choice，也需要转换
                    if (originalBody.tool_choice) {
                        qwenBody.tool_choice = this.transformToolChoice(originalBody.tool_choice);
                    }
                }

                // 创建新的请求体
                const newBody = JSON.stringify(qwenBody);

                // 修改请求头，确保移除可能冲突的Content-Length头
                const headers = new Headers(init?.headers);
                headers.set('Authorization', `Bearer ${this.apiKey}`);
                headers.set('Content-Type', 'application/json');
                // 删除可能存在的Content-Length头，让fetch自动计算
                headers.delete('Content-Length');

                // 发送转换后的请求
                const response = await fetch(qwenUrl, {
                    ...init,
                    headers,
                    body: newBody
                });

                if (!response.ok) {
                    throw new Error(`Qwen API error: ${response.status} ${response.statusText}`);
                }

                // 转换响应
                const qwenResponse = await response.json();
                const anthropicResponse = this.transformResponse(qwenResponse);

                // 创建新的Response对象
                return new Response(JSON.stringify(anthropicResponse), {
                    status: response.status,
                    statusText: response.statusText,
                    headers: response.headers
                });
            }

            // 对于其他请求，直接转发
            return fetch(url, init);
        };
    }

    /**
     * 创建兼容的Anthropic客户端
     */
    create(): Anthropic {
        return new Anthropic({
            apiKey: this.apiKey, // 这里传入任意值，实际认证在fetch中处理
            baseURL: this.baseURL,
            fetch: this.createCustomFetch()
        });
    }
}

